package com.ling.recipeassistant.ui.screens

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.ling.recipeassistant.R
import com.ling.recipeassistant.data.model.Recipe
import com.ling.recipeassistant.data.repository.RecipeRepository
import com.ling.recipeassistant.ui.components.RecipeCard
import com.ling.recipeassistant.ui.viewmodel.RecipeDetailViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecipeDetailScreen(
    recipe: Recipe,
    onBackClick: () -> Unit,
    onFavoriteClick: () -> Unit = {},
    viewModel: RecipeDetailViewModel = hiltViewModel()
) {
    val context = LocalContext.current
    val uiState by viewModel.uiState.collectAsState()
    
    // 监听收藏状态变化
    LaunchedEffect(recipe.id) {
        viewModel.loadRecipeDetails(recipe.id)
    }
    
    // 使用ViewModel中的菜谱数据，如果没有则使用传入的recipe
    val currentRecipe = uiState.recipe ?: recipe
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(currentRecipe.name) },
                navigationIcon = {
                    IconButton(onClick = onBackClick) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = { 
                        viewModel.toggleFavorite(currentRecipe.id)
                        onFavoriteClick()
                    }) {
                        Icon(
                            imageVector = if (currentRecipe.isFavorite) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
                            contentDescription = "收藏",
                            tint = if (currentRecipe.isFavorite) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        if (uiState.isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues),
                contentPadding = PaddingValues(bottom = 16.dp)
            ) {
                // 菜谱图片
                item {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(250.dp)
                    ) {
                        // 检查是否为本地图片资源
                        if (currentRecipe.imageUrl.endsWith(".png") || currentRecipe.imageUrl.endsWith(".jpg") || currentRecipe.imageUrl.endsWith(".jpeg")) {
                            val resourceId = getLocalImageResourceId(currentRecipe.imageUrl)
                            if (resourceId != 0) {
                                Image(
                                    painter = painterResource(id = resourceId),
                                    contentDescription = currentRecipe.name,
                                    modifier = Modifier.fillMaxSize(),
                                    contentScale = ContentScale.Crop
                                )
                            } else {
                                Image(
                                    painter = painterResource(id = R.drawable.recipe_placeholder_1),
                                    contentDescription = currentRecipe.name,
                                    modifier = Modifier.fillMaxSize(),
                                    contentScale = ContentScale.Crop
                                )
                            }
                        } else {
                            // 网络图片（保留原有逻辑作为备用）
                            Image(
                                painter = painterResource(id = R.drawable.recipe_placeholder_1),
                                contentDescription = currentRecipe.name,
                                modifier = Modifier.fillMaxSize(),
                                contentScale = ContentScale.Crop
                            )
                        }
                        
                        // 评分和评论数
                        Row(
                            modifier = Modifier
                                .align(Alignment.BottomStart)
                                .padding(16.dp)
                                .background(
                                    color = MaterialTheme.colorScheme.surface.copy(alpha = 0.8f),
                                    shape = RoundedCornerShape(8.dp)
                                )
                                .padding(8.dp),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.tertiary,
                                modifier = Modifier.size(20.dp)
                            )
                            Text(
                                text = String.format("%.1f", currentRecipe.rating),
                                style = MaterialTheme.typography.bodyMedium,
                                fontWeight = FontWeight.Bold
                            )
                            Text(
                                text = "(${currentRecipe.reviewCount}条评论)",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
                
                // 菜谱基本信息
                item {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = currentRecipe.name,
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(8.dp))
                        
                        Text(
                            text = currentRecipe.description,
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        // 菜谱元信息
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            RecipeInfoItem(
                                icon = Icons.Default.Schedule,
                                label = "烹饪时间",
                                value = "${currentRecipe.cookTime}分钟"
                            )
                            RecipeInfoItem(
                                icon = Icons.Default.Person,
                                label = "份量",
                                value = "${currentRecipe.servings}人份"
                            )
                            RecipeInfoItem(
                                icon = Icons.Default.TrendingUp,
                                label = "难度",
                                value = getDifficultyText(currentRecipe.difficulty)
                            )
                        }
                        
                        Spacer(modifier = Modifier.height(16.dp))
                        
                        // 标签
                        if (currentRecipe.tags.isNotEmpty()) {
                            Text(
                                text = "标签",
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.SemiBold
                            )
                            
                            Spacer(modifier = Modifier.height(8.dp))
                            
                            Row(
                                horizontalArrangement = Arrangement.spacedBy(8.dp),
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                currentRecipe.tags.forEach { tag ->
                                    AssistChip(
                                        onClick = { },
                                        label = { Text(tag) },
                                        colors = AssistChipDefaults.assistChipColors(
                                            containerColor = MaterialTheme.colorScheme.secondaryContainer
                                        )
                                    )
                                }
                            }
                        }
                    }
                }
                
                // 食材列表
                item {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "食材",
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(12.dp))
                        
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surfaceVariant
                            )
                        ) {
                            Column(
                                modifier = Modifier.padding(16.dp)
                            ) {
                                currentRecipe.ingredients.forEachIndexed { index, ingredient ->
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        verticalAlignment = Alignment.CenterVertically
                                    ) {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(8.dp)
                                        ) {
                                            Box(
                                                modifier = Modifier
                                                    .size(8.dp)
                                                    .background(
                                                        color = MaterialTheme.colorScheme.primary,
                                                        shape = CircleShape
                                                    )
                                            )
                                            Text(
                                                text = ingredient.name,
                                                style = MaterialTheme.typography.bodyMedium
                                            )
                                        }
                                        Text(
                                            text = "${ingredient.amount}${ingredient.unit}",
                                            style = MaterialTheme.typography.bodyMedium,
                                            fontWeight = FontWeight.Medium
                                        )
                                    }
                                    
                                    if (index < currentRecipe.ingredients.size - 1) {
                                        Spacer(modifier = Modifier.height(8.dp))
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 烹饪步骤
                item {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "烹饪步骤",
                            style = MaterialTheme.typography.titleLarge,
                            fontWeight = FontWeight.Bold
                        )
                        
                        Spacer(modifier = Modifier.height(12.dp))
                    }
                }
                
                // 步骤列表
                itemsIndexed(currentRecipe.steps) { index, step ->
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 16.dp, vertical = 4.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface
                        )
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.Top
                        ) {
                            // 步骤编号
                            Box(
                                modifier = Modifier
                                    .size(32.dp)
                                    .background(
                                        color = MaterialTheme.colorScheme.primary,
                                        shape = CircleShape
                                    ),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(
                                    text = "${index + 1}",
                                    style = MaterialTheme.typography.bodyMedium,
                                    fontWeight = FontWeight.Bold,
                                    color = MaterialTheme.colorScheme.onPrimary
                                )
                            }
                            
                            Spacer(modifier = Modifier.width(16.dp))
                            
                            // 步骤内容
                            Column(
                                modifier = Modifier.weight(1f)
                            ) {
                                Text(
                                    text = step.description,
                                    style = MaterialTheme.typography.bodyLarge
                                )
                                
                                if (step.timeMinutes != null) {
                                    Spacer(modifier = Modifier.height(4.dp))
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(4.dp)
                                    ) {
                                        Icon(
                                            imageVector = Icons.Default.Schedule,
                                            contentDescription = null,
                                            modifier = Modifier.size(16.dp),
                                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                        Text(
                                            text = "${step.timeMinutes}分钟",
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 底部间距
                item {
                    Spacer(modifier = Modifier.height(32.dp))
                }
            }
        }
    }
    
    // 错误对话框
    if (uiState.error != null) {
        AlertDialog(
            onDismissRequest = { viewModel.clearError() },
            title = { Text("错误") },
            text = { Text(uiState.error!!) },
            confirmButton = {
                TextButton(onClick = { viewModel.clearError() }) {
                    Text("确定")
                }
            }
        )
    }
}

@Composable
private fun RecipeInfoItem(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    label: String,
    value: String
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            textAlign = TextAlign.Center
        )
        
        Text(
            text = value,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Medium,
            textAlign = TextAlign.Center
        )
    }
}

private fun getDifficultyText(difficulty: com.ling.recipeassistant.data.model.Difficulty): String {
    return when (difficulty) {
        com.ling.recipeassistant.data.model.Difficulty.EASY -> "简单"
        com.ling.recipeassistant.data.model.Difficulty.MEDIUM -> "中等"
        com.ling.recipeassistant.data.model.Difficulty.HARD -> "困难"
    }
}

// 辅助函数：根据图片名称获取本地资源ID
private fun getLocalImageResourceId(imageName: String): Int {
    return when (imageName) {
        "wuhuarou.png" -> R.drawable.wuhuarou
        "mapodoufu.png" -> R.drawable.mapodoufu
        "tangculiji.png" -> R.drawable.tangculiji
        "gongbaojiding.png" -> R.drawable.gongbaojiding
        "baiqieji.png" -> R.drawable.baiqieji
        "chashaorou.png" -> R.drawable.chashaorou
        "fanqiedantang.png" -> R.drawable.fanqiedantang
        "dongguapaigutang.png" -> R.drawable.dongguapaigutang
        "yidalimian.png" -> R.drawable.yidalimian
        "niupai.png" -> R.drawable.niupai
        "pisa.png" -> R.drawable.pisa
        "qiaokelidangao.png" -> R.drawable.qiaokelidangao
        "tilamisu.png" -> R.drawable.tilamisu
        "makalong.png" -> R.drawable.makalong
        "suanrongxilanhua.png" -> R.drawable.suanrongxilanhua
        "disanxian.png" -> R.drawable.disanxian
        "jiandansanmingzhi.png" -> R.drawable.jiandansanmingzhi
        "yanmaizhou.png" -> R.drawable.yanmaizhou
        "ningmenfengmishui.png" -> R.drawable.ningmenfengmishui
        else -> R.drawable.recipe_placeholder_1 // 默认占位符
    }
} 